package com.fy.config;

import com.fy.service.EpcUserService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Order(1)
public class LoginInterceptor implements HandlerInterceptor {

    private Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);

    @Autowired
    private EpcUserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object object) throws Exception {
        String token = request.getHeader("token");
//        if(token.equals("123")){
//            return true;
//        }
//        if(!(object instanceof HandlerMethod)){
//            logger.debug("login 拦截 object：{}",object);
//            return true;
//        }
//        HandlerMethod handlerMethod=(HandlerMethod)object;
//        Method method=handlerMethod.getMethod();
//        logger.debug("login 拦截 method：{}",method);
//        //检查是否有passtoken注释，有则跳过认证
//        if (method.isAnnotationPresent(PassToken.class)) {
//            logger.debug("login 拦截 PassToken：{}",method);
//            PassToken passToken = method.getAnnotation(PassToken.class);
//            if (passToken.required()) {
//                return true;
//            }
//        }
//        logger.debug("login 拦截 UserLoginToken：{}",method);
//        UserLoginToken userLoginToken = method.getAnnotation(UserLoginToken.class);
//        Result result = Result.noLogin("未获取到用户信息");
//        String s = JSONObject.toJSONString(result);
//        String loginUrl =  request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort();
//        response.setContentType("application/json;charset=utf-8");
//        if (userLoginToken ==null || !userLoginToken.required()) {
//            // 执行认证
//            if (StringUtils.isBlank(token)) {
////                response.sendRedirect(request.getContextPath() + loginUrl);
//                response.getWriter().write(s);
//                return false;
//            }
//            // 获取 token 中的 user id
//            String userId;
//            try {
//                userId = JWT.decode(token).getAudience().get(0);
//            } catch (JWTDecodeException j) {
//                log.error(j.getMessage());
//                response.getWriter().write(s);
////                response.sendRedirect(request.getContextPath() + loginUrl);
//                return false;
////                throw new LoginException(HttpStatusEnum.LOGIN_TOKEN_ERROR);
//            }
//            Exception user = userService.queryById(Integer.parseInt(userId));
//            if (user == null) {
//                response.getWriter().write(s);
////                response.sendRedirect(request.getContextPath() + loginUrl);
//                return false;
////                throw new LoginException(HttpStatusEnum.USER_NOT_FOUND);
//            }
//            // 验证 token
//            try {
//                JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
//                jwtVerifier.verify(token);
//
//            } catch (JWTVerificationException e) {
//                log.error("登录失败：{}",e.getMessage());
//                response.getWriter().write(s);
////                response.sendRedirect(request.getContextPath() + loginUrl);
//                return false;
////                throw new LoginException(HttpStatusEnum.LOGIN_TOKEN_EXPIRE);
//            }
//            return true;
//        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        logger.info("postHandle...");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        logger.info("afterCompletion...");
    }

}
